package com.example.demo.service;

import com.example.demo.domian.Comment;
import com.example.demo.repository.CommentRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.Optional;

//业务类
@Service
@Transactional//添加事务注解，否则缓存更新出错
public class CommentService {
    @Autowired
    private CommentRepository commentRepository;

    /**
     * 根据id查询
     */
    //@Cacheable(cacheNames = "comment")//存放在名为comment的默认缓存中

    @Cacheable(cacheNames = "comment" ,unless = "#result==null")//结果为空不缓存
    public Comment findById(Integer id){
        Optional<Comment> byId=commentRepository.findById(id);
        if(byId.isPresent()){
            return byId.get();
        }
        return null;
    }

    //更新
    @CachePut(cacheNames = "comment",key="#result.id")
    public  Comment updateComment(Comment comment){
        int i=commentRepository.updateComment(comment.getAuthor(),comment.getId());
        Optional<Comment> byId= commentRepository.findById(comment.getId());
        if(byId.isPresent()){
            return byId.get();
        }
        return null;
    }


    //删除
    @CacheEvict(cacheNames = "comment")
    public void deleteComment(Integer id){
        commentRepository.deleteById(id);
    }




}
